<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      title="新增申领单"
      align="center"
      :visible.sync="innerDialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="申领类型"
          :label-width="formLabelWidth"
          prop="requisitionTypeCode"
          :error="errorMsg.requisitionTypeCode"
        >
          <el-select
            v-model="formData.requisitionTypeCode"
            placeholder="请选择"
            remote
            reserve-keyword
          >
            <el-option
              v-for="item in requisitionTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="申领人"
          :label-width="formLabelWidth"
          prop="requisitionPeopleId"
          :error="errorMsg.requisitionPeopleId"
        >
          <el-select
            v-model="formData.requisitionPeopleId"
            placeholder="请选择"
            clearable
            reserve-keyword
            filterable
            :remote-method="remoteUser"
            @change="(val) => selectRequisitionPeople(val)"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="是否需要归还"
          :label-width="formLabelWidth"
          prop="whetherReturnCode"
          :error="errorMsg.whetherReturnCode"
        >
          <el-select v-model="formData.whetherReturnCode" placeholder="请选择">
            <el-option
              v-for="item in whetherReturnList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="申领仓库"
          :label-width="formLabelWidth"
          prop="storageId"
          :error="errorMsg.storageId"
        >
          <el-select
            v-model="formData.storageId"
            placeholder="请选择入库仓库"
            filterable
            clearable
            @change="(val) => selectStorage(val)"
          >
            <el-option
              v-for="item in storageIdData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="用途"
          :label-width="formLabelWidth"
          prop="purpose"
          :error="errorMsg.purpose"
        >
          <el-input v-model="formData.purpose" type="textarea"></el-input>
        </el-form-item>
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          prop="remark"
          :error="errorMsg.remark"
        >
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>

        <el-divider class="el-divider-specail" content-position="left"
          ><span>申领物料</span>
          <el-button
            type="primary"
            style="margin-left: 20px"
            @click="choiceMaterial"
            >选择物料</el-button
          >
        </el-divider>
      </el-form>
      <div>
        <el-table :data="tableList">
          <el-table-column label="物料编号">
            <template slot-scope="scope">
              {{ scope.row.number }}
            </template>
          </el-table-column>
          <el-table-column label="物料名称">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="物料别名">
            <template slot-scope="scope">
              {{ scope.row.aliasName }}
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.size }}
            </template>
          </el-table-column>
          <el-table-column label="包装单位">
            <template slot-scope="scope">
              {{ scope.row.packingUnit }}
            </template>
          </el-table-column>
          <el-table-column label="存储条件">
            <template slot-scope="scope">
              {{ scope.row.storeCondition }}
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template slot-scope="scope">
              {{ scope.row.inventory }}
            </template>
          </el-table-column>
          <el-table-column label="申领数量">
            <template #header>
              <span style="color: red">*</span>
              <span>申领数量</span>
            </template>
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.count"
                autocomplete="off"
                :validate-event="false"
                placeholder="请输入"
                @blur="handleInputBlur(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectMaterialDialog
      v-if="dialogProductVisible"
      ref="SelectMaterialDialog"
      :dialog-product-visible.sync="dialogProductVisible"
      :query.sync="queryForm"
      @confirmSelected="confirmSelected"
    />
  </div>
</template>

<script>
import {
  create,
  update,
  get,
} from "../../../api/Material/MaterialRequisitionForm.js";
import { deepClone } from "@/utils";
import {getUserListNoPage} from "@/ModulePermission/api/Permission/PermissionUser.js";
import { getStorageList } from "../../../api/Material/Common.js";
import SelectMaterialDialog from "../../../components/SelectMaterialDialog.vue";
import { requisitionType, whetherReturn } from "../../../utils/const";
import _ from "lodash";
export default {
  name: "MaterialRequisitionFormEdit",
  components: { SelectMaterialDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("请选择是否归还"));
      }
    };
    return {
      loading: false,
      dialogProductVisible: false,
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      userList: [],
      tableList: [],
      storageIdData: [],
      requisitionType,
      requisitionTypeList: [],
      whetherReturn,
      whetherReturnList: [],
      queryForm: {
        status: 1,
        number: "",
        name: "",
        type: null,
        storageId: "",
        storageMaterialState: true,
      },
      initData: {
        id: 0,
        num: "",
        requisitionTypeCode: "",
        requisitionTypeName: "",
        requisitionPeopleId: "",
        requisitionPeopleName: "",
        whetherReturnCode: "",
        whetherReturnName: "",
        purpose: "",
        remark: "",
        requisitionTime: null,
        stateCode: 0,
        stateName: "",
        creatorId: 0,
        creatorName: "",
      },
      formData: {
        id: 0,
        num: "",
        requisitionTypeCode: "",
        requisitionTypeName: "",
        requisitionPeopleId: "",
        requisitionPeopleName: "",
        whetherReturnCode: "1",
        whetherReturnName: "",
        purpose: "",
        remark: "",
        requisitionTime: null,
        stateCode: 0,
        stateName: "",
        creatorId: 0,
        creatorName: "",
        storageId: "",
        storageName: "",
        requisitionFormDetailsList: [],
      },
      formDataRules: {
        storageId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        requisitionTypeCode: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        requisitionPeopleId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        whetherReturnCode: [
          {
            required: true,
            trigger: "blur",
            validator: validatePass,
          },
        ],
        purpose: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        requisitionTypeCode: "",
        requisitionTypeName: "",
        requisitionPeopleId: "",
        requisitionPeopleName: "",
        whetherReturnCode: "",
        whetherReturnName: "",
        purpose: "",
        remark: "",
        requisitionTime: "",
        stateCode: "",
        stateName: "",
        creatorId: "",
        creatorName: "",
      },
      errorMsg: {
        num: "",
        requisitionTypeCode: "",
        requisitionTypeName: "",
        requisitionPeopleId: "",
        requisitionPeopleName: "",
        whetherReturnCode: "",
        whetherReturnName: "",
        purpose: "",
        remark: "",
        requisitionTime: "",
        stateCode: "",
        stateName: "",
        creatorId: "",
        creatorName: "",
      },
    };
  },
  watch: {
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    handleInputBlur(row) {
      // 正则表达式：必须为正整数
      const reg = /^[1-9]\d*$/;
      if (!reg.test(row.count)) {
        this.$message.error("请输入正整数");
        row.count = null; // 重置为默认值
      }
      if (row.count > row.inventory) {
        this.$message.error("必须小于等于库存");
        row.count = null; // 重置为默认值
      }
    },
    // 选择物料
    choiceMaterial() {
      if (!this.formData.storageId) {
        this.$message.error("请选择仓库");
        return false;
      }
      this.queryForm.storageId = this.formData.storageId;
      this.dialogProductVisible = true;
    },
    confirmSelected(data) {
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].materialId = data[i].id;
          data[i].id = 0;
        }
        this.tableList = data;
      }
    },
    selectRequisitionPeople(val) {
      var obj = {};
      obj = this.userList.find(function(i) {
        return i.id === val;
      });
      this.formData.requisitionPeopleId = obj.id;
      this.formData.requisitionPeopleName = obj.name;
    },
    selectStorage(val) {
      var obj = {};
      obj = this.storageIdData.find(function(i) {
        return i.id === val;
      });
      this.formData.storageId = obj.id;
      this.formData.storageName = obj.name;
    },
    init() {
      this.requisitionTypeList = deepClone(this.requisitionType);
      this.whetherReturnList = deepClone(this.whetherReturn);

      getUserListNoPage({ userStatus: 1 })
        .then((res) => {
          this.userList = res.data;
        });
      getStorageList().then((res) => {
        if (res.data.dataList?.length > 0) {
          this.storageIdData = res.data.dataList.map((item) => {
            return {
              ...item,
              value: item.id,
            };
          });
        }
      });

      if (this.editId) {
        get({ id: this.editId }).then((res) => {
          console.log("[][][][][][][");
          console.log(res);
          this.formData = res.data;
          this.formData.requisitionTypeCode = String(
            res.data.requisitionTypeCode
          );
          this.formData.whetherReturnCode = String(res.data.whetherReturnCode);
          for (let i = 0; i < res.data.requisitionFormDetailsList.length; i++) {
            var data = res.data.requisitionFormDetailsList[i];
            res.data.requisitionFormDetailsList[i].number = data.materialNum;
            res.data.requisitionFormDetailsList[i].name = data.materialName;
          }
          this.tableList = deepClone(res.data.requisitionFormDetailsList);
        });
      } else {
        this.formData.requisitionPeopleId = this.$store.getters.currentUserId;
        this.formData.requisitionPeopleName = this.$store.getters.name;
      }
    },
    remoteUser(query) {
      getUserListNoPage({ name: query, userStatus: 1 })
        .then((res) => {
          this.userList = res.data;
        });
    },
    handleClose() {
      this.closeDialog();
    },
    cancel() {
      this.$emit("close");
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.cancel();
    },
    onSubmit: _.throttle(function() {
      this.formData.requisitionFormDetailsList = [];
      for (let i = 0; i < this.tableList.length; i++) {
        if (!this.tableList[i].count) {
          this.$message.error("申领数量不能为空");
          return false;
        }
        this.formData.requisitionFormDetailsList.push({
          materialId: this.tableList[i].materialId,
          count: this.tableList[i].count,
        });
      }

      var user = this.userList.find(
        (x) => x.id === this.formData.requisitionPeopleId
      );
      if (user !== undefined && user !== null) {
        this.formData.requisitionPeopleName = user.name;
      }
      var requisitionType = this.requisitionTypeList.find(
        (x) => x.value === this.formData.requisitionTypeCode
      );
      if (requisitionType !== undefined && requisitionType !== null) {
        this.formData.requisitionTypeName = requisitionType.name;
      }
      var whetherReturn = this.whetherReturnList.find(
        (x) => x.value === this.formData.whetherReturnCode
      );
      if (whetherReturn !== undefined && whetherReturn !== null) {
        this.formData.whetherReturnName = whetherReturn.name;
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    }, 5000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "requisitionTypeCode",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "requisitionTypeName",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "requisitionPeopleId",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "requisitionPeopleName",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "whetherReturnCode",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "whetherReturnName",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("purpose", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("requisitionTime", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("stateCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("stateName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorName", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
